#include <iostream>
#include <stdio.h>
#include <memory>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>


#define ERR_EXIT(m) \
    do\
    {\
        perror(m);\
        exit(EXIT_FAILURE);\
    }while(0) 
#define MSGMAX 8192
struct msgbuf1
{
    /* data */
    long mtypc;
    char mtext[MSGMAX];
};

void echo_srv(int msgid)
{
    int n=0;
    struct msgbuf1 msg;
    memset(&msg, 0, sizeof(msg));
    while(1){
        if((n = msgrcv(msgid, &msg, MSGMAX, 1, 0))<0)
            ERR_EXIT("msgrcv");
        
        int pid;
        pid = *((int *)msg.mtext);
        printf("rcv pid = %d\n", pid);
        fputs(msg.mtext+4, stdout);

        msg.mtypc = pid;
        msgsnd(msgid, &msg, n, 0);
        printf("send pid = %d\n", pid);
        memset(&msg, 0, sizeof(msg));
    }
}
int main(int argv, char**argc)
{
    printf("************  message queue server!!!   **************\n");
    /* add test code! */
    int msgid;
    msgid = msgget(1234, IPC_CREAT | 0666);
    if(msgid == -1)
        ERR_EXIT("msget");
    
    echo_srv(msgid);


    
    return 0;
}
